import {http} from "./http";
import {createPlainAddressService, eAddressTypeEnum, iAddressSyncMeta, iPlainAddressData} from "plain-design";
import {pathJoin} from "@peryl/utils/pathJoin";

export const address = createPlainAddressService({
  http,
  getAddress: async () => {
    const resp = await fetch(pathJoin(__webpack_public_path__, 'libs/address.json'));
    const list = await resp.json();
    const format = (list: iPlainAddressData[]): iAddressSyncMeta[] => {
      return list.map(i => ({
        label: i.name,
        code: i.code,
        type: (Deep2Type as any)[i.deep],
        parentCode: i.parentCode,
        ...!i.children ? {} : { children: format(i.children) },
      }));
    };
    return format(list as any);
  }
});

const Deep2Type = {
  0: eAddressTypeEnum.province,
  1: eAddressTypeEnum.city,
  2: eAddressTypeEnum.district,
} as const;
